<?php

namespace app\modules\weixin\controllers;

use app\common\services\StaticServices;
use app\models\IntegralGood;
use app\models\IntegralRecord;
use app\models\Member;
use app\modules\weixin\controllers\common\BaseController;
use Yii;
use yii\base\Exception;
use yii\web\Response;

class GoodsController extends BaseController
{
    /**
     * 商品列表
     * @return array
     */
    public function actionGoodList()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        try {
            $p = intval(Yii::$app->request->get('p', 1));
            $good_list = IntegralGood::find();

            $page_size = 6;
            $total_count = $good_list->count();
            $total_page = ceil($total_count / $page_size);

            $list = $good_list->offset(($p - 1) * $page_size)->orderBy(['update_time' => SORT_DESC])->limit($page_size)->asArray()->all();
            $list['total_page'] = $total_page;
            return ['code' => 200, 'data' => $list];
        } catch (Exception $e) {
            return ['code' => -200, 'msg' => $e->getMessage()];
        }
    }

    /**
     * 商品详情
     * @return array
     */
    public function actionGoodInfo()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        try {
            $good_id = intval(Yii::$app->request->get('good_id'));
            if (!$good_id) {
                throw new Exception('参数有误');
            }
            $good_info = IntegralGood::find()->where(['id' => $good_id])->one();
            if (!$good_info) {
                throw new Exception('数据有误');
            }
            return ['code' => 200, 'data' => $good_info];
        } catch (Exception $e) {
            return ['code' => -200, 'msg' => $e->getMessage()];
        }
    }

    /**
     * 个人兑换商品列表
     * @return array
     */
    public function actionMemberGood()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        try {
            $member_id = intval(Yii::$app->request->post('member_id'));
            $session_member = Yii::$app->session->get('member_info');
            $p = intval(Yii::$app->request->post('p', 1));
            if (!$member_id || $member_id != $session_member['id']) {
                throw new Exception('参数有误');
            }
            $member_goods = IntegralRecord::find()->joinWith('good')->where(['member_id' => $member_id]);

            $page_size = 5;
            $total_count = $member_goods->count();
            $total_page = ceil($total_count / $page_size);

            $list = $member_goods->offset(($p - 1) * $page_size)->orderBy(['create_time' => SORT_DESC])->limit($page_size)->asArray()->all();
            $list['total_page'] = $total_page;
            return ['code' => 200, 'data' => $list];
        } catch (Exception $e) {
            return ['code' => -200, 'msg' => $e->getMessage()];
        }
    }

    /**
     * 个人兑换商品详情
     * @return array
     */
    public function actionMemberGoodInfo()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        try {
            $member_id = intval(Yii::$app->request->get('member_id'));
            $good_id = intval(Yii::$app->request->get('good_id'));
            $session_member = Yii::$app->session->get('member_info');
//
            if (!$member_id || $member_id != $session_member['id']) {
                throw new Exception('参数有误');
            }
            if (!$good_id) {
                throw new Exception('商品参数有误');
            }

            $member_good = IntegralRecord::find()->joinWith('good')->where(['member_id' => $member_id, 'good_id' => $good_id])->asArray()->one();
            return ['code' => 200, 'data' => $member_good];
        } catch (Exception $e) {
            return ['code' => -200, 'msg' => $e->getMessage()];
        }
    }

    /**
     * 兑换商品
     * @return array
     */
    public function actionExchangeGood()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        try {
            $member_id = intval(Yii::$app->request->post('member_id'));
            $good_id = intval(Yii::$app->request->post('good_id'));
            $session_member = Yii::$app->session->get('member_info');

            if (!$member_id || $member_id != $session_member['id']) {
                throw new Exception('参数有误');
            }

            if (!$good_id) {
                throw new Exception('商品参数有误');
            }
            $integral_record = IntegralRecord::find()->where(['member_id' => $member_id, 'good_id' => $good_id])->one();
            $member_info = Member::find()->where(['id' => $session_member['id']])->one();
            if ($integral_record) {
                throw new Exception('此商品您已经兑换过了');
            }

            $good_info = IntegralGood::find()->where(['id' => $good_id])->one();

            if ($member_info->member_integral < $good_info->good_integral) {
                throw new Exception('您的积分不足');
            }

            $connection = IntegralRecord::getDb();
            $transaction = $connection->beginTransaction();
            $good = IntegralGood::tableName();
            $tmp_sql = "SELECT good_integral,good_num,id FROM {$good} WHERE id={$good_id} FOR UPDATE";
            $good_info = $connection->createCommand($tmp_sql)->queryOne();
            $check_code = strtolower(StaticServices::getRandChar(6));
            $record_info = new IntegralRecord();
            $record_info->member_id = $member_id;
            $record_info->good_id = $good_id;
            $record_info->good_integral = $good_info['good_integral'];
            $record_info->record_status = 0;
            $record_info->check_code = $check_code;
            $record_info->update_time = time();
            $record_info->create_time = time();
            if ($record_info->save(0)) {
                $good_info = IntegralGood::find()->where(['id' => $good_id])->one();
                $good_info->good_num -= 1;
                $good_info->update_time = time();
                $good_info->save(0);

                $member_info = Member::find()->where(['id' => $session_member['id']])->one();
                $member_info->member_integral -= $good_info['good_integral'];
                $member_info->update_time = time();
                $member_info->save(0);
            }
            $transaction->commit();
            return ['code' => 200, 'msg' => '兑换成功,请及时领取'];
        } catch (Exception $e) {
//            $transaction->rollBack();
            return ['code' => -200, 'msg' => $e->getMessage()];
        }
    }
}
